const jwt = require('jsonwebtoken')
const config = require('../config')
const { query } = require('../config/database')

// JWT验证中间件
const authenticateToken = async (req, res, next) => {
  try {
    const authHeader = req.headers['authorization']
    const token = authHeader && authHeader.split(' ')[1]

    if (!token) {
      return res.error('访问令牌不存在', 'MISSING_TOKEN', 401)
    }

    // 验证token
    const decoded = jwt.verify(token, config.jwt.secret)

    // 查询用户信息
    const users = await query(
      'SELECT id, email, username, avatar_url, role, is_vip, vip_type, vip_expire_date, coins FROM users WHERE id = ?',
      [decoded.userId]
    )

    if (users.length === 0) {
      return res.error('用户不存在', 'USER_NOT_FOUND', 401)
    }

    const user = users[0]

    // 检查VIP是否过期
    if (
      user.is_vip &&
      user.vip_expire_date &&
      new Date(user.vip_expire_date) < new Date()
    ) {
      await query('UPDATE users SET is_vip = false WHERE id = ?', [user.id])
      user.is_vip = false
    }

    req.user = user
    next()
  } catch (error) {
    if (error.name === 'JsonWebTokenError') {
      return res.error('无效的访问令牌', 'INVALID_TOKEN', 401)
    }
    if (error.name === 'TokenExpiredError') {
      return res.error('访问令牌已过期', 'TOKEN_EXPIRED', 401)
    }
    next(error)
  }
}

// 可选认证中间件（不要求必须登录）
const optionalAuth = async (req, res, next) => {
  try {
    const authHeader = req.headers['authorization']
    const token = authHeader && authHeader.split(' ')[1]

    if (token) {
      const decoded = jwt.verify(token, config.jwt.secret)
      const users = await query(
        'SELECT id, email, username, avatar_url, role, is_vip, vip_type, vip_expire_date, coins FROM users WHERE id = ?',
        [decoded.userId]
      )

      if (users.length > 0) {
        const user = users[0]

        // 检查VIP是否过期
        if (
          user.is_vip &&
          user.vip_expire_date &&
          new Date(user.vip_expire_date) < new Date()
        ) {
          await query('UPDATE users SET is_vip = false WHERE id = ?', [user.id])
          user.is_vip = false
        }

        req.user = user
      }
    }

    next()
  } catch (error) {
    // 可选认证中的错误不阻断请求
    next()
  }
}

// VIP权限验证
const requireVip = (req, res, next) => {
  if (!req.user) {
    return res.error('请先登录', 'AUTHENTICATION_REQUIRED', 401)
  }

  if (!req.user.is_vip) {
    return res.error('需要VIP权限', 'VIP_REQUIRED', 403)
  }

  next()
}

// 管理员权限验证
const requireAdmin = async (req, res, next) => {
  try {
    if (!req.user) {
      return res.error('请先登录', 'AUTHENTICATION_REQUIRED', 401)
    }

    // 检查是否为管理员（简单检查邮箱或者添加 role 字段检查）
    const adminEmails = ['admin@novel.com', 'admin@example.com']
    const isAdmin =
      adminEmails.includes(req.user.email) || req.user.role === 'admin'

    if (!isAdmin) {
      return res.error('需要管理员权限', 'ADMIN_REQUIRED', 403)
    }

    next()
  } catch (error) {
    next(error)
  }
}

// 生成JWT token
const generateToken = userId => {
  return jwt.sign({ userId }, config.jwt.secret, {
    expiresIn: config.jwt.expiresIn
  })
}

// 验证token（不查询数据库）
const verifyToken = token => {
  try {
    return jwt.verify(token, config.jwt.secret)
  } catch (error) {
    return null
  }
}

module.exports = {
  authenticateToken,
  optionalAuth,
  requireVip,
  requireAdmin,
  generateToken,
  verifyToken
}
